package com.diorsunion.hedge.algo;

import com.diorsunion.hedge.domain.AccountManager;
import com.diorsunion.hedge.dal.entity.stock.StockPrice;
import com.diorsunion.hedge.dal.entity.TradeLog;
import com.diorsunion.hedge.domain.MACD;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * MACD
 * 金叉买，死叉卖
 * Created by wanglaoshi on 2016/4/16.
 */
public class Oper10 extends Operation {

    public Oper10(Map<String, Integer> params) {
        super(params);
    }

    private static final Set<MACD> buy_set = Sets.newHashSet(new MACD(MACD.Type.buttom_divergence, 1), new MACD(MACD.Type.JINCHA, 3));
    private static final Set<MACD> sell_set = Sets.newHashSet(new MACD(MACD.Type.top_divergence, 1), new MACD(MACD.Type.SICHA, 3));

    private StockPrice.PriceType priceType = StockPrice.PriceType.OPEN;//用收盘价来计算
    private AccountManager account_period_begin = null;//周期记录日的账户情况,静态止损

    @Override
    public void oper(AccountManager accountManager, List<AccountManager> account_per_days) {
        if (account_per_days.size() < 2) {
            return;
        }
        AccountManager account_yes = account_per_days.get(account_per_days.size() - 2);
        accountManager.stockPool.forEach((stock, num) -> {
            StockPrice stockPrice = stock.getStockPrice(accountManager.date);
            //用昨天的MACD作为买卖标准
            StockPrice stockPrice_yes = stock.getStockPrice(account_yes.date);
            if (stockPrice_yes == null) {
                return;
            }
            int trade_num = (int) (accountManager.getTotalValue(StockPrice.PriceType.OPEN)/stockPrice.open);

            if ( stockPrice_yes.ex.macd>0 ) {
                TradeLog t1 = accountManager.trade(stock, trade_num, StockPrice.PriceType.OPEN);
                tradeLogs.add(t1);
                double open = stockPrice.open;

                double price = open*1.1d;
                TradeLog l = accountManager.trade(stock,-trade_num,StockPrice.PriceType.CLOSE);
                if(l==null){
                    TradeLog t2 = accountManager.trade(stock, -trade_num, price);
                    tradeLogs.add(t2);
                }else {
                    tradeLogs.add(l);
                }
            }
            if (stockPrice_yes.ex.macd<0){
                TradeLog t1 = accountManager.trade(stock, -trade_num, StockPrice.PriceType.OPEN);
                tradeLogs.add(t1);
                double open = stockPrice.open;
                double price = open*0.9d;
                TradeLog l = accountManager.trade(stock,trade_num,StockPrice.PriceType.CLOSE);
                if(l==null){
                    TradeLog t2 = accountManager.trade(stock, trade_num, StockPrice.PriceType.CLOSE);
                    tradeLogs.add(t2);
                }else {
                    tradeLogs.add(l);
                }
            }
        });
    }

    @Override
    public String getDesc() {
        return "MACD买卖法";
    }
}
